package imvu.rbox.object
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	
	import imvu.rbox.global.GStatic;

	public class UserFaceLoader extends Sprite
	{
		private var faceWidth:Number;
		private var faceHeight:Number;
		private var faceLoader:Loader;
		
		public function UserFaceLoader(ww:Number = 40, hh:Number = 50)
		{			
			faceWidth = ww;
			faceHeight = hh;
		}
		
		public function LoadFace(path:String):void
		{
			if(!faceLoader)
			{
				GStatic.Trace("取到IMG地址:" + path);
				LoadUserFace(path);
			}
		}	
		
		public function RemoveFace():void
		{
			if(faceLoader)
			{
				this.faceLoader.parent.removeChild(faceLoader);
				this.faceLoader = null;
			}
		}		
		
		//-----------------------------------------------------
		
		private function LoadUserFace(path:String):void
		{		
			if(path)
			{
				GStatic.Trace("开始下载图像");
				if(path.length > 0)
				{
					this.faceLoader = new Loader();
					this.faceLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoadFaceError);
					//this.faceLoader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadFaceError);
					this.faceLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadFaceDone);
					this.faceLoader.load(new URLRequest(path), new LoaderContext(true));
				}
			}
		}
				
		private function DeleteFaceListener():void
		{
			this.faceLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onLoadFaceError);
			this.faceLoader.contentLoaderInfo.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadFaceError);
			this.faceLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadFaceDone);
		}
		
		private function onLoadFaceError(e:*):void
		{
			GStatic.Trace("LOAD USER FACE Error!!" + e);
			DeleteFaceListener();	
		}
		
		private function onLoadFaceDone(e:Event):void
		{	
			GStatic.Trace("读取图像成功");
			DeleteFaceListener();
			
			this.addEventListener(Event.ENTER_FRAME, onInitFace);
		}
		
		private function onInitFace(e:Event):void
		{
			if(this.faceLoader.width > 0 && this.faceLoader.height > 0)
			{
				GStatic.Trace("显示图像成功");
				this.removeEventListener(Event.ENTER_FRAME, onInitFace);
				
				this.faceLoader.width = this.faceWidth;
				this.faceLoader.height = this.faceHeight;
				
				//this.addChild(this.faceLoader);
				//this.parent.addChild(this);
				this.faceLoader.x = this.x;
				this.faceLoader.y = this.y;
				
				this.parent.addChild(faceLoader);				
			}
		}
	}
}